<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.CalibrationPlanInfo"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="innerDialogFormVisible"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        label-width="140px"
        :model="formData"
        :rules="formDataRules"
        status-icon
      >
        <el-form-item
          :label="dataList.CalibrationPlanProgramme"
          prop="deviceCalibrationId"
          :error="errorMsg.deviceCalibrationId"
        >
          <el-select
            v-model="formData.deviceCalibrationId"
            :placeholder="dataList.Placeholder"
            @change="selChange"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="dataList.PlanName"
          prop="name"
          :error="errorMsg.name"
        >
          <el-input v-model="formData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.PlanendDate"
          prop="endDate"
          :error="errorMsg.endDate"
        >
          <el-date-picker
            v-model="formData.endDate"
            type="date"
            :placeholder="dataList.SelectDateTime"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <div class="base-content-operate" style="width: 100%">
          <el-input
            v-model="deviceNameNum"
            :placeholder="dataList.EnterDevice"
            class="input-with-select"
            style="width: 250px; float: left"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <el-button
            type="primary"
            style="margin-left: 5px; float: left"
            @click="batchSetting"
            >{{ btn.BatchSetting }}</el-button
          >
        </div>
        <br />
        <div style="width: 100%">
          <el-table
            :key="refreshData"
            :data="listData"
            element-loading-text="Loading"
            height="430"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column :label="dataList.DeviceNumber">
              <template slot-scope="scope">
                {{ scope.row.num }}
              </template>
            </el-table-column>
            <el-table-column
              :label="
                $i18n.locale === 'en'
                  ? dataList.DeviceEName
                  : dataList.DeviceName
              "
            >
              <template slot-scope="scope">
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.DeviceSpecifications">
              <template slot-scope="scope">
                {{ scope.row.specifications }}
              </template>
            </el-table-column>
            <el-table-column :label="dataList.DevicePersonResponsibleId">
              <template slot-scope="scope">
                {{ scope.row.personResponsibleName }}
              </template>
            </el-table-column>

            <el-table-column
              :label="dataList.CalibrationPlanDate"
              width="140px"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isCalibration === 0">/</span>
                <span v-else-if="scope.row.isCalibration === 1">{{
                  scope.row.calibrationPlanDate
                }}</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Week">
              <template slot-scope="scope">
                <span v-if="scope.row.isCalibration === 0">/</span>
                <span v-else-if="scope.row.isCalibration === 1">{{
                  scope.row.cycle + scope.row.cycleName
                }}</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.CalibrationPersonName">
              <template slot-scope="scope">
                <span v-if="scope.row.isCalibration === 0">/</span>
                <span v-else-if="scope.row.isCalibration === 1">{{
                  scope.row.calibrationPersonName
                }}</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.IsCalibrationName">
              <template slot-scope="scope">
                <span v-if="scope.row.isCalibration === 0" style="color: red">{{
                  scope.row.isCalibrationName
                }}</span>
                <span v-else-if="scope.row.isCalibration === 1">{{
                  scope.row.isCalibrationName
                }}</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column :label="dataList.Operation">
              <template slot-scope="scope">
                <div class="base-table-operation">
                  <el-link
                    style="margin-left: 5px"
                    size="mini"
                    type="primary"
                    @click="setting(scope.row)"
                    >{{ btn.Setting }}</el-link
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit(10)">{{
          btn.Save
        }}</el-button>
        <el-button type="primary" style="width: 140px" @click="onSubmit(20)">{{
          btn.SaveAndSubmit
        }}</el-button>
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
      <DeviceCalibrationPlanSettingDialog
        v-if="settingVisible"
        ref="DeviceCalibrationPlanSettingDialog"
        :dialog-form-visible.sync="settingVisible"
        :data-objcet.sync="dataObjcet"
        :devce-dto.sync="devceDto"
        @settingDialogClose="settingDialogClose"
      />
      <DeviceCalibrationPlanSettingDialog
        v-if="settingPitchVisible"
        ref="DeviceCalibrationPlanPitchSettingDialog"
        :dialog-form-visible.sync="settingPitchVisible"
        @settingDialogClose="settingDialogClose"
      />
    </el-dialog>
  </div>
</template>

<script>
import { create, update } from "../../../api/DeviceCalibrationPlan.js";
import { getList as getCalibrationList } from "../../../api/DeviceCalibrationInfo";
import DeviceCalibrationPlanSettingDialog from "./DeviceCalibrationPlanSettingDialog.vue";
import { getList } from "../../../api/DeviceCalibration.js";
export default {
  name: "DeviceCalibrationPlanAddDialog",
  components: { DeviceCalibrationPlanSettingDialog },
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    calibrationId: {
      type: Number,
      default: 0,
    },
    from: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      devceDto: {},
      dataObjcet: {},
      list: [],
      tableDatas: [],
      deviceNameNum: "",
      loading: false,
      settingPitchVisible: false,
      settingVisible: false,
      innerDialogFormVisible: false,
      formLabelWidth: "100px",
      refreshData: 0,
      options: [],
      initData: {
        deviceCalibrationId: null,
        name: "",
        endDate: null,
        creator: this.$store.getters.currentUserId,
        creatorName: this.$store.getters.name,
      },
      // 限制日期
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      formData: {
        id: 0,
        deviceCalibrationId: null,
        name: "",
        endDate: null,
        creator: this.$store.getters.currentUserId,
        creatorName: this.$store.getters.name,
      },
      formDataRules: {
        deviceCalibrationId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        endDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        deviceCalibrationId: "",
        name: "",
        endDate: "",
      },
      errorMsg: {
        deviceCalibrationId: "",
        name: "",
        endDate: "",
      },
    };
  },
  computed: {
    listData() {
      return this.list.filter((record) => {
        return (
          record.num.includes(this.deviceNameNum) ||
          record.name.includes(this.deviceNameNum)
        );
      });
    },
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {
    dialogFormVisible(val) {
      this.innerDialogFormVisible = val;
    },
    innerDialogFormVisible(val) {
      this.$emit("update:dialogFormVisible", val);
    },
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    this.init();
  },
  methods: {
    selChange(val) {
      getCalibrationList(
        { calibrationId: val },
        { pageIndex: 1, pageSize: 100000 }
      ).then((res) => {
        this.list = res.data.dataList;
        for (let i = 0; i < this.list.length; i++) {
          this.list[i].isCalibration = "";
          this.list[i].cycle = "";
          this.list[i].cycleName = "";
        }
      });
    },
    init() {
      // 查询已生效校准方案
      getList({ status: 30 }, { pageIndex: 1, pageSize: 100000 }).then(
        (res) => {
          this.options = res.data.dataList;
          if (this.calibrationId > 0) {
            this.formData.deviceCalibrationId = this.calibrationId;
            this.selChange(this.formData.deviceCalibrationId);
          }
        }
      );
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    settingDialogClose(data) {
      for (let i = 0; i < this.idList.length; i++) {
        for (let o = 0; o < this.list.length; o++) {
          if (this.idList[i] === this.list[o].id) {
            if (data.isCalibration === 0) {
              this.list[o].calibrationPlanDate = null;
              this.list[o].cycle = null;
              this.list[o].cycleName =
                this.$i18n.locale === "en" ? "Year" : "年";
              this.list[o].calibrationPersonName = null;
              this.list[o].calibrationPerson = 0;
              this.list[o].isCalibration = data.isCalibration;
              this.list[o].isCalibrationName = this.$t(
                "ModuleDevice.Device.Deny"
              );
            } else {
              this.list[o].calibrationPlanDate = data.calibrationPlanDate;
              this.list[o].cycle = data.cycle;
              this.list[o].cycleName = data.cycleName;
              this.list[o].calibrationPersonName = data.calibrationPersonName;
              this.list[o].calibrationPerson = data.calibrationPerson;
              this.list[o].isCalibration = data.isCalibration;
              this.list[o].isCalibrationName = this.$t(
                "ModuleDevice.Device.Correct"
              );
            }
          }
        }
      }
      this.$nextTick(() => {
        this.refreshData++;
      });
    },
    // 设置
    setting(row) {
      this.idList = [];
      this.idList.push(row.id);
      this.deviceDto = row.deviceDto;
      this.dataObjcet.isCalibration = row.isCalibration;
      this.dataObjcet.calibrationPlanDate = row.calibrationPlanDate;
      this.dataObjcet.cycle = row.cycle;
      this.dataObjcet.calibrationPerson = row.calibrationPerson;
      this.dataObjcet.cycleName = row.cycleName;
      this.dataObjcet.calibrationPersonName = row.calibrationPersonName;
      this.settingVisible = true;
    },
    // 批量设置
    batchSetting() {
      if (this.tableDatas === null || this.tableDatas.length === 0) {
        this.$message.warningthis.$t("ModuleDevice.Device.PleaseSelectData");
        return false;
      }
      this.idList = this.tableDatas.map((item) => item.id);
      this.settingPitchVisible = true;
    },
    cancel() {
      this.$parent.getList();
      this.innerDialogFormVisible = false;
    },
    closeDialog() {
      this.cancel();
    },
    onSubmit(status) {
      if (this.list === null || this.list.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Message.TableDataNull"));
        return false;
      }
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].isCalibration === "") {
          this.$message.warningthis.$t(
            "ModuleDevice.Message.CalibrationInfoNotNull"
          );
          return false;
        }
      }
      this.formData.deviceCalibrationPlanInfoDtos = this.list;
      this.formData.status = status;
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  if (this.from === 0) {
                    this.closeDialog();
                  } else {
                    this.$router.push("/DeviceCalibrationPlanList");
                  }
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("name", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("endDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("calibrationNum", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("status", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creator", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("assertDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
